/*
 * @Author: your name
 * @Date: 2021-09-15 09:32:35
 * @LastEditTime: 2022-11-08 21:04:54
 * @LastEditors: zshawk1982
 * @Description: In User Settings Edit
 * @FilePath: \media_system\app.js
 */
const Koa = require("koa");
const { bodyParser } = require("@koa/bodyparser");
const cors = require("@koa/cors");
const Router = require("@koa/router");

const koajwt = require("koa-jwt");
const serve = require('koa-static');
const path = require('path');
const router = new Router();
const user = require("./routes/user");
const knowledge = require("./routes/knowledge");
const food = require("./routes/food");
const recipe = require("./routes/recipe");
const dietRecord = require("./routes/dietRecord");
const bloodglucose = require("./routes/bloodglucose");
const hemoglobin = require("./routes/hemoglobin");
const { sequelize } = require("./database/index");
const { koaSwagger } = require('koa2-swagger-ui')
const swagger = require('./utils/swagger')
const schedule = require('node-schedule');
const timeScript = require('./utils/timeScript')
const { Knowledge, Food } = require("./database/index");
const Redis = require("ioredis");
const redis = new Redis();
const app = new Koa();
// const { historyApiFallback } = require('koa2-connect-history-api-fallback');

//数据库同步操作
(async () => {
  await sequelize.sync({ force: false });
})();

//跨域请求
app.use(
  cors({
    origin(ctx) {
      return "*";
    },
  })
);

//配置静态目录,提供app需要的隐私协议和服务协议页面
// console.log(1111111111,path.join(__dirname + "/public/privacy"))
app.use(serve(path.join(__dirname + "/public/privacy")));

//配置history路由重定向中间件，避免前端404问题，前端为history路由时需要
// app.use(historyApiFallback({ whiteList: ['/api/user','/api/knowledge','/api/food','/api/dietRecord','/api/recipe','/api/bloodglucose','/api/hemoglobin'] }));

//处理post请求
app.use(bodyParser());

//安装jwt验证
app.use(
  koajwt({ secret: "zshawk1982" }).unless({
    // 登录，注册，swagger接口不需要验证
    // path: [/^\/user\/login/,/^\/user\/register/,/^\/swagger/],
    path: [/^\/user/, /^\/swagger/, /^\/dietRecord/, /^\/food/, /^\/knowledge/, /^\/recipe/, /^\/bloodglucose/, /^\/hemoglobin/],
  })
);

//swagger配置
app.use(swagger.routes(), swagger.allowedMethods())
app.use(koaSwagger({
  routePrefix: '/swagger',
  swaggerOptions: {
    url: '/swagger.json',
  },
}))



//定时任务
/** 定义规则,cron表达式*/
// *  *  *  *  *  *
// ┬ ┬ ┬ ┬ ┬ ┬
// │ │ │ │ │  |
// │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
// │ │ │ │ └───── month (1 - 12)
// │ │ │ └────────── day of month (1 - 31)
// │ │ └─────────────── hour (0 - 23)
// │ └──────────────────── minute (0 - 59)
// └───────────────────────── second (0 - 59, OPTIONAL)
/**每隔30分钟去更新知识redis方法*/
schedule.scheduleJob('*/30 * * * *', () => {
  timeScript.updateKnowledgeRedisViews()
})
/**每天的凌晨2点去更新食物redis方法*/
schedule.scheduleJob('0 0 2 * * *', () => {
  timeScript.updateFoodRedis()
})
/**每天的凌晨3点去检查用户的年龄是否需要更新totalkal的值方法*/
schedule.scheduleJob('0 0 3 * * *', () => {
  timeScript.updateUserTotalKal()
})


//加载子路由
router.use("/user", user.routes());
router.use("/knowledge", knowledge.routes());
router.use("/food", food.routes());
router.use("/dietRecord", dietRecord.routes());
router.use("/recipe", recipe.routes());
router.use("/bloodglucose", bloodglucose.routes());
router.use("/hemoglobin", hemoglobin.routes());

app.use(router.routes(), router.allowedMethods());



//服务器监听端口
app.listen(8081, async () => {
  //项目已启动需执行初始化redis,将知识浏览量存入到redis中
  let knowledges = await Knowledge.findAll({
    attributes: ['knowledgeId', 'views']
  });
  for(let i=0;i<knowledges.length;i++){
    await redis.hset('knowledgeviews', knowledges[i].knowledgeId, knowledges[i].views ? knowledges[i].views : 0)
  }
  //项目已启动需执行初始化redis,将记录用食物名存入redis中
  let foods = await Food.findAll({
    attributes: ['foodId', 'foodName', 'unit']
  })
  for (let i = 0; i < foods.length; i++) {
    if(foods[i].unit==null||foods[i].unit==''||foods[i].unit==" "){
      foods[i].unit=0
    }
    await redis.sadd('foodInfos',foods[i].foodName+"#"+foods[i].foodId+"_"+foods[i].unit)
  }
});
